<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
    
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    HashMap探究 |  Yolin
  </title>
  <meta name="generator" content="hexo-theme-yilia-plus">
  
  <link rel="shortcut icon" href="/favicon.png" />
  
  
<link rel="stylesheet" href="/css/style.css">

  
<script src="/js/pace.min.js"></script>


  

  

<link rel="alternate" href="/atom.xml" title="Yolin" type="application/atom+xml">
</head>

</html>

<body>
  <div id="app">
    <main class="content">
      <section class="outer">
  <article id="post-HashMap探究-1" class="article article-type-post" itemscope
  itemprop="blogPost" data-scroll-reveal>

  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  HashMap探究
</h1>
  

    </header>
    

    
    <div class="article-meta">
      <a href="/2021/01/16/HashMap%E6%8E%A2%E7%A9%B6-1/" class="article-date">
  <time datetime="2021-01-16T06:45:02.000Z" itemprop="datePublished">2021-01-16</time>
</a>
      
  <div class="article-category">
    <a class="article-category-link" href="/categories/Java/">Java</a>
  </div>

      
      
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">1.4k字</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">4分钟</span>
        </span>
    </span>
</div>

      
    </div>
    

    
    
    <div class="tocbot"></div>





    

    <div class="article-entry" itemprop="articleBody">
      


      

      
      <h2 id="HashMap实现原理"><a href="#HashMap实现原理" class="headerlink" title="HashMap实现原理"></a>HashMap实现原理</h2><p>HashMap是基于Hash算法实现的，是通过put(key,value)存储，get(key)来获取，当传入key时，会根据key 的HashCode方法计算Hash值，根据Hash值将value保存在bucket里，当计算的Hash值相同时称为Hash冲突，HashMap的做法是用链表和红黑树来存储Hash值相同的value，是当数组大于等于64，链表长度达到8时会转换为红黑树（泊松分布）</p>
<h2 id="用String作为key有什么好处？"><a href="#用String作为key有什么好处？" class="headerlink" title="用String作为key有什么好处？"></a>用String作为key有什么好处？</h2><p>HashMap是通过key的HashCode来确定value的存储位置，因为字符串是不可变的，所以在创建的时候，它的Hashcode被缓存下来，不需要计算，所以相比其它对象更快。</p>
<h2 id="Hash的概念"><a href="#Hash的概念" class="headerlink" title="Hash的概念"></a>Hash的概念</h2><p>Hash的基本概念就是把任意长度的输入通过一个hash算法之后，映射成固定长度的输出</p>
<a id="more"></a>
<h2 id="HashMap初始化容量大小是多少？"><a href="#HashMap初始化容量大小是多少？" class="headerlink" title="HashMap初始化容量大小是多少？"></a>HashMap初始化容量大小是多少？</h2><p>通过查看源码可以发现：</p>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2021-01-05_11-31-15.jpg" alt=""></p>
<!--more-->
<p><strong>初始化数组大小</strong>：<strong>16</strong> (2的4次方)</p>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2021-01-05_11-34-35.jpg" alt=""></p>
<p><strong>加载因子</strong>：衡量一个数组是否被填满，等于1，则证明数组已经被填满，等于0证明数组还是空的。</p>
<p>默认是<strong>0.75</strong></p>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2021-01-05_11-39-23.jpg" alt=""></p>
<p>threshold：<strong>阈值</strong>，数组到达某一个阈值时开始进行扩容</p>
<p>所以是<strong>12</strong></p>
<h2 id="长度为什么必须是2的幂？"><a href="#长度为什么必须是2的幂？" class="headerlink" title="长度为什么必须是2的幂？"></a>长度为什么必须是2的幂？</h2><p>HashMap存取时，需要对当前key，计算数组下标</p>
<p>HashMap为了减少碰撞，就要尽量把数据平均分配，(n - 1) &amp; hash 这个操作如果在n为2的N次幂的情况下是等同于 hash % n 取余数的值，而使用与运算效率高于 hash%n 取余数的值。</p>
<p>总结：HashMap这里采用的是用与运算符替换传统的取模方式，从而大大提高效率，但与运算符进行计算的前提是必须2的幂次方</p>
<p>然后通过下面的方法执行操作</p>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2021-01-05_11-59-32.jpg" alt=""></p>
<h2 id="HashMap的put过程"><a href="#HashMap的put过程" class="headerlink" title="HashMap的put过程"></a>HashMap的put过程</h2><ul>
<li>根据key 的hashCode方法计算hash值</li>
<li>根据hash值与数组长度-1进行与运算得到index值</li>
<li>如果索引处为空，则直接插入对应数组中，否则，判断是否是红黑树</li>
<li>如果是，则红黑树插入，否则遍历链表，若长度大于8，则将链表转换为红黑树，转成功之后再插入。</li>
</ul>
<h2 id="HashMap的get过程"><a href="#HashMap的get过程" class="headerlink" title="HashMap的get过程"></a>HashMap的get过程</h2><ul>
<li>根据key 的hashCode方法计算hash值</li>
<li>根据hash值与数组长度-1进行与运算得到index值（数据的存储位置）</li>
<li>根据index找到链表的头结点，遍历对应的链表，若key值相等（这里用的equals方法判断），返回对应的value值，否则返回null</li>
</ul>
<h2 id="HashMap什么时候扩容，扩多少？"><a href="#HashMap什么时候扩容，扩多少？" class="headerlink" title="HashMap什么时候扩容，扩多少？"></a>HashMap什么时候扩容，扩多少？</h2><ul>
<li>首次扩容：HashMap初始化后首次插入数据时，先发生resize扩容，再插入数据；因使用默认构造方法初始化HashMap,HashMap一开始会返回一个空数组，且加载因子为0，所以第一次扩容的容量为默认值16，阈值是12.（注意：java7是在存入数据前进行判断是否扩容，而java8是在存入数据后再进行扩容的判断）</li>
<li>当前存入数据大于阈值时进行扩容，此时是先插入数据再扩容，容量扩大为原来的2倍。</li>
<li>数组长度小于64，链表长度大于8时会进行扩容，如果数组长度大于等于64时才会将链表转换为红黑树。</li>
</ul>
<h2 id="ConcurrentHashMap"><a href="#ConcurrentHashMap" class="headerlink" title="ConcurrentHashMap"></a>ConcurrentHashMap</h2><p>JDK1.7中采用了一种分段锁的机制，底层实现是一个segment数组，每个segment的底层结构和HashMap相似，也是数组加链表</p>
<p>首先将数据分为一段一段的存储，然后给每一段数据配一把锁（ReentrantLock），当一个线程占用锁访问其中一段数据时，其他段的数据也能被其他线程访问.</p>
<p>JDK1.8中摒弃了Segment，新的实现也是数组+链表+红黑树，在put方法里使用了CAS + synchronized进行同步。如果插入元素为空则用CAS进行插入，插入元素不为空，则对当前位置对象进行加锁，加锁后再进行后续操作。</p>
<p>好处：synchronized只需要锁住当前链表的头结点，理论上数组长度有多大，并发操作线程数就有多少，效率高。</p>
<h2 id="ConcurrentHashMap和HashTable区别"><a href="#ConcurrentHashMap和HashTable区别" class="headerlink" title="ConcurrentHashMap和HashTable区别"></a>ConcurrentHashMap和HashTable区别</h2><ul>
<li>HashTable底层采用数组+链表，ConcurrentHashMap在JDK1.8采用数组+链表+红黑树，数组是HashMap的主体，链表是为解决哈希冲突存在的</li>
<li>1.8的ConcurrentHashMap可以并发控制使用synchronized和CAS来操作，HashTable使用synchronized来保证线程安全，效率非常低</li>
</ul>
<h2 id="CAS（比较并交换）"><a href="#CAS（比较并交换）" class="headerlink" title="CAS（比较并交换）"></a>CAS（比较并交换）</h2><p>CAS包含3个参数：</p>
<ul>
<li>内存值  V　　</li>
<li>旧的预期值  A　　</li>
<li>新值  B</li>
</ul>
<p>　　当且仅当V值等于A值时，将V的值改为B值，如果V值和A值不同，说明已经有其他线程做了更新，则当前线程什么都不做，最后返回当前V的真实值。CAS操作是抱着乐观的态度进行的（乐观锁），它总是认为自己可以成功地完成操作。</p>
<h2 id="ThreadLocal"><a href="#ThreadLocal" class="headerlink" title="ThreadLocal"></a>ThreadLocal</h2><p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2021-01-16_12-58-48.jpg" alt=""></p>
<p>ThreadLocal使各个线程之间相互隔离，每个线程有自己独立的变量。可以理解为ThreadLocal不是针对程序的全局变量，而是针对线程的全局变量</p>
<p><strong>原理</strong>：</p>
<p>ThreadLocal内部维护了一个Map变量ThreadLocalMap，对应的就是每个Thread对象中的属性ThreadLocals，他的key就是当前线程本身，value就是我们set进来的值，调用get时，会将当前线程作为key，然后从ThreadLocalMap中获取</p>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2021-01-16_13-47-13.jpg" alt=""></p>

      
      <!-- reward -->
      
    </div>
      <!-- copyright -->
      
    <footer class="article-footer">
      
      
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/HashMap/" rel="tag">HashMap</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E9%9B%86%E5%90%88/" rel="tag">集合</a></li></ul>


    </footer>

  </div>

  
  
  <nav class="article-nav">
    
      <a href="/2021/01/20/Java%E7%9F%A5%E8%AF%86%E6%B1%87%E6%80%BB%EF%BC%88%E6%97%A5%E5%B8%B8%E6%9B%B4%E6%96%B0%EF%BC%89/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            Java知识汇总（日常更新）
          
        </div>
      </a>
    
    
      <a href="/2021/01/10/JVM%E6%8E%A2%E7%A9%B6/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">JVM探究</div>
      </a>
    
  </nav>


  

  
  
<!-- valine评论 -->
<div id="vcomments-box">
    <div id="vcomments">
    </div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src='https://cdn.jsdelivr.net/npm/valine@1.3.10/dist/Valine.min.js'></script>
<script>
    new Valine({
        el: '#vcomments',
        notify: false,
        verify: '',
        app_id: '',
        app_key: '',
        path: window.location.pathname,
        avatar: 'mp',
        placeholder: '给我的文章加点评论吧~',
        recordIP: true
    });
    const infoEle = document.querySelector('#vcomments .info');
    if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
        infoEle.childNodes.forEach(function (item) {
            item.parentNode.removeChild(item);
        });
    }
</script>
<style>
    #vcomments-box {
        padding: 5px 30px;
    }

    @media screen and (max-width: 800px) {
        #vcomments-box {
            padding: 5px 0px;
        }
    }

    #vcomments-box #vcomments {
        background-color: #fff;
    }

    .v .vlist .vcard .vh {
        padding-right: 20px;
    }

    .v .vlist .vcard {
        padding-left: 10px;
    }
</style>

  

  
  
  

</article>
</section>
      <footer class="footer">
  <div class="outer">
    <ul class="list-inline">
      <li>
        &copy;
        2020-2021
        张金
      </li>
      <li>
        
      </li>
    </ul>
    <ul class="list-inline">
      <li>
        
        
        <span>
  <i>PV:<span id="busuanzi_value_page_pv"></span></i>
  <i>UV:<span id="busuanzi_value_site_uv"></span></i>
</span>
        
      </li>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
        <img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/beian.png">
        <a href="https://beian.miit.gov.cn"  style="color:#f72b07" target="_blank">陕ICP备20002449号</a>
      </li>

    </ul>
  </div>
</footer>
    <div class="to_top">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>
      </div>
    </main>
      <aside class="sidebar">
        <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="Yolin"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/playlist">歌单</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/video">视频</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/about">关于我</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友情链接</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
      </aside>
      <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="/images/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="/images/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
      
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/jquery.justifiedGallery.min.js"></script>


<script src="/js/lazyload.min.js"></script>


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<script src="/js/share.js"></script>




<script>
  try {
    var typed = new Typed("#subtitle", {
    strings: ['肠断月明红豆蔻,','月似当时,','人似当时否？'],
    startDelay: 1500,
    typeSpeed: 200,
    loop: true,
    backSpeed: 40,
    showCursor: true
    });
  } catch (err) {
  }
  
</script>




<script src="/js/tocbot.min.js"></script>

<script>
  // Tocbot_v4.7.0  http://tscanlin.github.io/tocbot/
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer:'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto',
    onClick: (e) => {
      $('.toc-link').removeClass('is-active-link');
      $(`a[href=${e.target.hash}]`).addClass('is-active-link');
      $(e.target.hash).scrollIntoView();
      return false;
    }
  });
</script>


<script>
  var ayerConfig = {
    mathjax: true
  }
</script>


<script src="/js/ayer.js"></script>


<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>



<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
      tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
  });

  MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
      for(i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
      }
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/mathjax@2.7.6/unpacked/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>


<script type="text/javascript" src="https://js.users.51.la/20544303.js"></script>
  </div>
</body>

</html>